import SparkMd5 from 'spark-md5'
import type { App, Component } from 'vue'
import { h, createApp } from 'vue'
import { NIcon, NSpin } from 'naive-ui'

// 计算文件md5
export const getFileMd5 = (file: Blob): Promise<string> => {
  const spark = new SparkMd5.ArrayBuffer()
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = (e) => {
      const result = e.target?.result as ArrayBuffer
      if (result) {
        spark.append(result)
        resolve(spark.end())
      } else {
        reject('Error: file is empty')
      }
    }
    fileReader.onerror = (e) => {
      reject(e.target?.error)
    }
    fileReader.readAsArrayBuffer(file)
  })
}

// 并发限制promise
export const promisePool = async (promises: Array<() => Promise<any>>, n: number) => {
  return await Promise.all(
    Array.from({ length: n }, async () => {
      while (promises.length > 0) {
        await promises.shift()?.()
      }
    })
  )
}

// 渲染icon
export const renderIcon = (icon: Component) => {
  return () => h(NIcon, null, { default: () => h(icon) })
}

// 全局Loader
export class Loader {
  static root: App<Element> | null

  static show() {
    const loadingContainer = document.querySelector('#__loader__')
    if (!loadingContainer || Loader.root || loadingContainer.classList.contains('loading')) {
      return
    }
    loadingContainer.classList.add('loading')
    Loader.root = createApp(NSpin)
    Loader.root.mount(loadingContainer)
  }

  static hide() {
    const loadingContainer = document.querySelector('#__loader__')
    loadingContainer?.classList.remove('loading')
    Loader.root && Loader.root.unmount()
    Loader.root = null
  }
}

// 复制到粘贴板
export const copyText = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    window.$message.success('复制成功')
  } catch (error) {
    window.$message.error('复制失败')
  }
}
